package io.github.lee.app.unsplash.ui.detail.photo

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.graphics.drawable.toDrawable
import io.github.lee.app.unsplash.databinding.ItemTopicPhotoBinding
import io.github.lee.app.unsplash.repository.domain.Photo
import io.github.lee.app.unsplash.util.BlurHashDecoder
import io.github.lee.core.ui.adapter.DataBindingAdapter
import io.github.lee.core.ui.ba.coilLoad
import kotlin.math.roundToInt

class PhotoDetailAdapter : DataBindingAdapter<Photo, ItemTopicPhotoBinding>() {
    override fun onCreateDataBinding(
        context: Context,
        inflater: LayoutInflater,
        parent: ViewGroup,
        viewType: Int
    ): ItemTopicPhotoBinding =
        ItemTopicPhotoBinding.inflate(inflater, parent, false)


    override fun onItemHolder(binding: ItemTopicPhotoBinding, item: Photo) {
        binding.item = item

        val ratio = item.width * 1F / item.height
        val bw = 4
        val bh = (4 / ratio + 0.5).roundToInt()
        val hash = BlurHashDecoder.decode(item.blurHash, bw, bh)
        val placeholder = hash?.toDrawable(context.resources)
        binding.ivPhoto.coilLoad(
            item.urls?.regular, 180,
            placeholder = placeholder,
            error = placeholder
        )
    }

}